<?php

namespace app\api\admin\v1\service\finder;

use zhanshop\App;
use extend\docker\Volume;
use zhanshop\server\Request;
use zhanshop\server\Response;
use zhanshop\ShellCommand;

class Cloudvolume extends BaseFinder
{
    protected $limits = [5000];
    protected $search = false;

    protected $rowToolbar = [
        [
            'event' => 'open',
            'ico' => '&#xe642;',
            'title' => '拉取代码',
            'method' => '',
            'page' => './page/docker/pull-volume.html',
        ],
        [
            'event' => 'delete',
            'ico' => '&#xe640;',
            'title' => '删除',
            'method' => '',
            'page' => '',
        ],
    ];

    protected $headToolbar = [
        [
            'event' => 'add',
            'ico' => '&#xe608;',
            'title' => '创建',
            'method' => '',
            'page' => './page/docker/create-volume.html',
        ],
        [
            'event' => 'deletes',
            'ico' => '&#xe640;',
            'title' => '删除',
            'method' => '',
            'page' => '',
        ],
    ];

    protected function getCols(string $schma){
        $cols = [
            'name' => array (
                'field' => 'name',
                'title' => '数据卷名',
                'input_type' => 'readonly',
                'width' => 180,
            ),
            'driver' => array (
                'field' => 'driver',
                'title' => '驱动',
                'width' => 170,
                'value' => [
                    'local' => 'local',
                ],
                'null' => 'no',
                'input_type' => 'readonly',
            ),
            'mountpoint' => array (
                'field' => 'mountpoint',
                'title' => '位置',
                'width' => 320,
                'input_type' => 'hidden',
                'null' => 'no',
                'value' => []
            ),
            'createdat' => array (
                'field' => 'createdat',
                'title' => '创建时间',
                'input_type' => 'hidden',
                'null' => 'no',
                'width' => 220,
            ),
        ];
        return $cols;
    }

    public function data(int $page, int $limit, array $order, array $search)
    {
        $volumes = App::make(Volume::class)->getList();
        $list = $volumes['volumes'] ?? [];
        return [
            'total' => count($list),
            'list' => $list
        ];
    }

    public function post(Request $request, Response $response)
    {
        $data = $request->validateData($request->post('base'), [
            'name' => 'required',
            'driver' => 'required',
            'giturl' => 'required | url',
            'gituser' => 'required',
            'gitpwd' => 'required',
        ])->getData();
        $data['name'] = strtolower($data['name']);
        if(preg_match('/^[a-zA-Z0-9_]+$/', $data['name']) == false) App::error()->setError('数据卷名仅能包含字母数字和下划线');
        if(App::database()->model("clouds_volume")->where(['name' => $data['name']])->find()){
            App::database()->model("clouds_volume")->where(['name' => $data['name']])->update([
                'giturl' => $data['giturl'],
                'gituser' => $data['gituser'],
                'gitpwd' => $data['gitpwd'],
            ]);
        }else{
            App::database()->model("clouds_volume")->insert([
                'name' => $data['name'],
                'giturl' => $data['giturl'],
                'gituser' => $data['gituser'],
                'gitpwd' => $data['gitpwd'],
            ]);
        }
        // 创建数据卷
        App::make(Volume::class)->create($data["name"], $data["driver"]);
        return [];
    }

    // git密码保存位置 /root/.git-credentials
    // 这里的内容是进行url编码的
    //       httpszhang768617998%40qq.com:xxx@gitee.com
    // 格式： https://zhang768617998%40qq.com:XXXXX@gitee.com
    // docker volume create --name my-volume --driver local-persist --opt "mountpoint=/path/to/your/desired/location"

    /**
     * 删除数据卷
     * @param Request $request
     * @param Response $response
     * @return array
     * @throws \Exception
     */
    public function delete(Request $request, Response $response){
        $input = $request->post();
        $pks = $input['pk'];
        foreach($pks as $pk){
            App::make(Volume::class)->delete($pk);
        }
        return [];
    }

    /**
     * git标签获取
     * @param Request $request
     * @param Response $response
     * @return array
     */
    public function tags(Request $request, Response $response)
    {
        $tags = [];
        $data = $request->validateRule([
            'name' => 'required'
        ])->getData();
        $gitPath = '/var/www/docker/volumes/'.$data['name'].'/_data';
        if(file_exists($gitPath) == false){
            $gitPath = '/var/lib/docker/volumes/'.$data['name'].'/_data';
        }
        //$gitPath = '/Users/zhangqiquan/Documents/phpdev/benchun_marketing/vendor/zhanshop/framework';
        $files = scandir($gitPath);
        $files = array_diff($files, ['.', '..']);
        $empty = true;
        if (!empty($files)) {
            chdir($gitPath);
            $empty = false;
            ShellCommand::exec('git fetch --tags', function ($echo){});
            $cmd = "git tag";
            $output = \Swoole\Coroutine\System::exec($cmd)['output'];
            $outputs = array_filter(explode("\n", $output));
            chdir(__DIR__);
            rsort($outputs);
            $tags = $outputs;
        }
        return [
            'tags' => $tags,
            'empty' => $empty
        ];
    }

    public function checkout(Request $request, Response $response)
    {
        $data = $request->validateRule([
            'name' => 'required',
            'tab' => 'required',
        ])->getData();

        $gitPath = '/var/www/docker/volumes/'.$data['name'].'/_data';
        if(file_exists($gitPath) == false){
            $gitPath = '/var/lib/docker/volumes/'.$data['name'].'/_data';
        }
        //$gitPath = '/Users/zhangqiquan/Documents/phpdev/benchun_marketing/vendor/zhanshop/framework';

        chdir($gitPath);
        $msg = "";
        ShellCommand::exec('git checkout '.$data['tab'], function ($echo) use (&$msg){
            $msg .= $echo;
        });
        chdir(__DIR__);
        return [
            'msg' => $msg
        ];
    }
}